package ru.usu.gv.view;

import com.sun.j3d.utils.picking.PickCanvas;
import com.sun.j3d.utils.picking.PickResult;
import com.sun.j3d.utils.picking.behaviors.PickMouseBehavior;

import ru.usu.gv.core.GraphEngine;
import ru.usu.gv.uicomponents.UIElementBase;

import javax.media.j3d.Bounds;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.Node;

/**
 @author Sergey Pupyrev 
 08.01.2007
 */

public class GraphPickBehavior extends PickMouseBehavior
{

    public GraphPickBehavior(Canvas3D canvas, BranchGroup root, Bounds bounds)
    {
        super(canvas, root, bounds);
        this.setSchedulingBounds(bounds);
        this.pickCanvas.setTolerance(5.0f);
        setMode(PickCanvas.GEOMETRY);
    }

    @Override
    public void updateScene(int xpos, int ypos)
    {
        Node shape = null;

        pickCanvas.setShapeLocation(mevent);
        try
        {
            PickResult pr[] = pickCanvas.pickAllSorted();
            if (pr != null)
            {
                PickListener pickListener = GraphEngine.getInstance().getPickListener();
                for (int i = 0; i < pr.length; i++)
                {
                    if ((shape = pr[i].getNode(PickResult.SHAPE3D)) != null)
                    {
                        if (shape.isLive())
                        {
                            UIElementBase pickedElement = (UIElementBase)shape.getUserData();
                            if (pickedElement != null && pickListener.picked(mevent, pickedElement))
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
        catch (javax.media.j3d.CapabilityNotSetException e)
        {
            throw new RuntimeException(e);
        }
    }

}
